<?php
namespace app\api\model;
/**
 * @Author: user
 * @Date:   2019-04-02 09:55:07
 * @Last Modified by:   user
 * @Last Modified time: 2019-04-04 11:58:39
 */
use think\Model;
use think\Db;
use app\admin\model\AccessModel;
use app\admin\model\AdminMenuModel;
use app\admin\model\AuthAccessModel;
use app\admin\model\AccessVersionsMenuModel;
/**
 * 
 */
class ApiAuthorizationModel extends Model
{
	/**
	 * 读取授权菜单列表
	 * @return [type] [description]
	 */
	public function getAccessMenus($userId)
	{
		//获取用户信息
		$accessModel=new AccessModel();
		$userInfo=$accessModel->getUserInfo($userId); 
		//获取原始菜单列表
		$adminM=new AdminMenuModel();
		$mainMenus=$adminM->getAllMenus();
		$mainMenus=json_decode($mainMenus,true);
		$adminMenus=$this->getValuesByKey($mainMenus,'id');		
		//读取管理员菜单
		$roleM=new AuthAccessModel();
		$roleMenus=$roleM->getAllMenusByRoleId($userInfo['role_id']);
		$roleMenus=json_decode($roleMenus,true);
		$roleMenus=$this->getValuesByKey($roleMenus,'menu_id');
		//获取交集
		$menus=array_intersect($adminMenus,$roleMenus);
		//提取菜单  原始菜单数据
		$resultMenus=[];
		foreach ($mainMenus as $key => $value) {
			if(in_array($value['id'],$menus)){
				$resultMenus[]=$value;
			}
		}

		//替换原始菜单名称  遍历原始菜单
		$aliasList = Db::name('menu_alias')->where('company_id',$userInfo['company_id'])->select()->toArray();
		foreach ($resultMenus as $key => $value) {
			$alias = $this->getMenuAliasName($aliasList,$value['id']);
			if(!empty($alias)){
				$resultMenus [$key] ['name'] = $alias; 
			}
		}
		return $resultMenus;
	}

	/**
	 * 获取菜单别名 返回菜单别名
	 */
	private function getMenuAliasName($list,$menuId)
	{
		$aliasNmae = '';
		foreach ($list as $key => $value) {
			if($menuId == $value['menu_id']){
				$aliasNmae = $value['alias'];
				break;
			}
		}
		return $aliasNmae;
	}

	/**
	 * 获取数组中的列值的一维数组
	 * @param  [type] $list[][] 关联数组
	 * @param  [type] $column  健名
	 * @return [type]       [description]
	 */
	protected function getValuesByKey($list,$column,$result=[])
	{
		if(!is_array($list)){
			return $result;
		}
		foreach ($list as $key => $value) {
			if(is_array($value)){
				$result=$this->getValuesByKey($value,$column,$result);
			}else{
				if($key==$column){
					$result[]=$list[$column];
					break;
				}
			}
		}
		return $result;
	}

}